package module

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "os"
    "path"
    "strconv"
    "strings"
    "yi-shou-backstage/config"
    "yi-shou-backstage/errmsg"
    "yi-shou-backstage/model"
    "yi-shou-backstage/module/result"
    "yi-shou-backstage/util"
)

func UploadUserImageControl(req *gin.Context) (int, string, interface{}) {
    // 获取图片信息
    file, err := req.FormFile("image")
    if err != nil {
        util.LogEntry.Errorf("参数错误，error = %s \n", err)
        return errmsg.PARAM_ERROR, errmsg.GetErrorByCode(errmsg.PARAM_ERROR), nil
    }

    // 校验图片格式
    suffix := strings.ToLower(path.Ext(file.Filename))
    if suffix != ".jpg" && suffix != ".png" && suffix != ".jpeg" {
        util.LogEntry.Errorf("图片格式错误")
        return errmsg.PHOTO_FORMAT_ERROR, errmsg.GetErrorByCode(errmsg.PHOTO_FORMAT_ERROR), nil
    }

    pwd, _ := os.Getwd()  // 项目根路径
    filePath := fmt.Sprintf("%s/static/img/%s", pwd, file.Filename)
    err = req.SaveUploadedFile(file, filePath);
    if err != nil {
        util.LogEntry.Errorf("保存图片失败，error = %s \n", err)
        return errmsg.UPLOAD_FAILD, errmsg.GetErrorByCode(errmsg.UPLOAD_FAILD), nil
    }

    // 拼接图片路径
    serverAddress := fmt.Sprintf("%s:%d", config.Conf.Server.Host, config.Conf.Server.Port)
    photo := fmt.Sprintf("%s/static/img/%s", serverAddress, file.Filename)

    // 把图片路径保存到数据库
    img := model.CreateImage(model.Image{Url: photo})
    if img == nil {
        util.LogEntry.Errorf("新增用户图片素材失败 \n")
        return errmsg.CREATE_USER_IMAGE_ERROR, errmsg.GetErrorByCode(errmsg.CREATE_USER_IMAGE_ERROR), nil
    }

    return errmsg.SUCCESS, errmsg.GetErrorByCode(errmsg.SUCCESS), img
}

func PutUserImageControl(req *gin.Context) (int, string, interface{}) {
    // 获取图片id
    id, err := strconv.Atoi(req.Param("id"))
    if err != nil {
        util.LogEntry.Errorf("数据类型转换错误, error = %s \n", err)
        return errmsg.DATA_TYPE_CONV_ERROR, errmsg.GetErrorByCode(errmsg.DATA_TYPE_CONV_ERROR), nil
    }
    var params model.Image
    err = req.ShouldBindJSON(&params)
    if err != nil {
        util.LogEntry.Errorf("参数格式错误, error = %s, param = %s \n", err, params)
        return errmsg.PARAM_FORMAT_ERROR, errmsg.GetErrorByCode(errmsg.PARAM_FORMAT_ERROR), nil
    }

    // 校验参数
    img := model.GetImage(id)
    if img == nil {
        util.LogEntry.Errorf("图片不存在，id = %s \n", id)
        return errmsg.IMAGE_IS_NOT_EXIST, errmsg.GetErrorByCode(errmsg.IMAGE_IS_NOT_EXIST), nil
    }

    // 更新图片数据
    data := model.UpdateImage(id, model.Image{Collect: params.Collect})
    if data == nil {
        util.LogEntry.Errorf("更新图片信息失败，error = %s \n", err)
        return errmsg.UPDATE_IMAGE_ERROR, errmsg.GetErrorByCode(errmsg.UPDATE_IMAGE_ERROR), nil
    }
    return errmsg.SUCCESS, errmsg.GetErrorByCode(errmsg.SUCCESS), data
}

// 用户图片列表
func GetUserImagesControl(req *gin.Context) (int, string, interface{}) {
    // 获取参数
    page, err := strconv.Atoi(req.DefaultQuery("page", "-1"))
    per_page, err := strconv.Atoi(req.DefaultQuery("per_page", "-1"))
    collect, err := strconv.ParseBool(req.DefaultQuery("collect", "false"))
    if err != nil {
        util.LogEntry.Errorf("数据类型转换失败, error = %s \n", err)
        return errmsg.DATA_TYPE_CONV_ERROR, errmsg.GetErrorByCode(errmsg.DATA_TYPE_CONV_ERROR), nil
    }
    params := model.Image{Page: page, PerPage: per_page, Collect: collect}

    // 枚举用户图片数据
    total, rows := model.ListUserImages(params)
    if total == 0 {
        util.LogEntry.Errorf("查询图片失败 \n")
        return errmsg.LIST_IMAGES_ERROR, errmsg.GetErrorByCode(errmsg.LIST_IMAGES_ERROR), nil
    }

    data := result.ListImagesResponse{TotalCount: total, Page: params.Page, PerPage: params.PerPage, Results: rows}
    return errmsg.SUCCESS, errmsg.GetErrorByCode(errmsg.SUCCESS), data
}

// 删除图片素材
func DeleteUserImageControl(req *gin.Context) (int, string, interface{}) {
    // 获取图片id
    id, err := strconv.Atoi(req.Param("id"))
    if err != nil {
        util.LogEntry.Errorf("数据类型转换错误, error = %s \n", err)
        return errmsg.DATA_TYPE_CONV_ERROR, errmsg.GetErrorByCode(errmsg.DATA_TYPE_CONV_ERROR), nil
    }

    // 验证 该id 对应的图片是否存在
    img := model.GetImage(id)
    if img == nil {
        util.LogEntry.Errorf("图片不存在，id = %s \n", id)
        return errmsg.IMAGE_IS_NOT_EXIST, errmsg.GetErrorByCode(errmsg.IMAGE_IS_NOT_EXIST), nil
    }

    // 根据 id 删除图片
    data := model.DeleteImage(id)
    if data == nil {
        util.LogEntry.Errorf("删除图片失败，img_id = %d \n", id)
        return errmsg.DELETE_IMAGE_ERROR, errmsg.GetErrorByCode(errmsg.DELETE_IMAGE_ERROR), nil
    }
    return errmsg.SUCCESS, errmsg.GetErrorByCode(errmsg.SUCCESS), data
}